package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map.Entry;
import java.util.Random;

import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

import rmi.Answer;
import rmi.Question;
import rmi.Session;

public class GUIQuestion extends JPanel{
	
	private static final long serialVersionUID = 1L;
	private ArrayList<Question> questions;
	private Session session;
	private int currentQuestion;
	private JLabel lbCount;
	private JTextArea lbQuestion;
	private JLabel lbImage;
	private ArrayList<JRadioButton> arrayJradio;
	private ArrayList<Integer> answerID;
	private JButton next, prev, summit;
	private JPanel answerPanel;
	private ButtonGroup group;
	
	public GUIQuestion(Session session) {
		this.session = session;
		setBorder(new EmptyBorder(10, 10, 10, 10));
		setLayout(new BorderLayout());
		setOpaque(false);
		
		lbCount = new JLabel();
		lbCount.setFont(lbCount.getFont().deriveFont(20f));
		lbCount.setForeground(new Color(30,30,30));
		
		lbQuestion = new CustomJTextArea();
		
		lbImage = new JLabel();
		
		arrayJradio = new ArrayList<>();
		answerID = new ArrayList<>();
		
		group = new  ButtonGroup();
		
		answerPanel = new JPanel();
		answerPanel.setLayout(new BoxLayout(answerPanel, BoxLayout.Y_AXIS));
		answerPanel.setOpaque(false);
		
		next = new CustomJButton(">", 40, 40, Color.WHITE, CustomJButton.DARKER,
				Color.DARK_GRAY, 0, true, true);
		next.addActionListener(new nextAction());
		prev = new CustomJButton("<", 40, 40, Color.WHITE, CustomJButton.DARKER,
				Color.DARK_GRAY, 0, true, true);
		prev.addActionListener(new prevAction());
		summit = new CustomJButton("S", 40, 40, Color.WHITE, CustomJButton.DARKER,
				Color.DARK_GRAY, 0, true, true);
		summit.addActionListener(new SummitAction());
		//addtoPanel
		JPanel questionPanel = new JPanel(new GridBagLayout());
		questionPanel.setOpaque(false);
		
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.BOTH;
		c.gridx = 0;
		c.gridy = 0;
		c.weightx = 1;
		questionPanel.add(lbCount,c);
		c.gridx = 0;
		c.gridy = 1;
		c.gridwidth = 2;
		questionPanel.add(lbQuestion,c);
		
		c.gridx = 0;
		c.gridy = 2;
		c.gridwidth = 2;
		questionPanel.add(lbImage, c);
		
		c.gridx = 0;
		c.gridy = 3;
		c.gridwidth = 1;
		questionPanel.add(new JLabel("Các câu trả lời:"),c);
		
		c.gridx = 0;
		c.gridy = 4;
		c.gridwidth = 2;
		questionPanel.add(answerPanel,c);
		
		JPanel buttonPanel = new JPanel(new BorderLayout());
		buttonPanel.setOpaque(false);
		JPanel centerButtons = new JPanel(new FlowLayout(FlowLayout.CENTER));
		centerButtons.setOpaque(false);
		JPanel rightButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		rightButtons.setOpaque(false);
		
		centerButtons.add(prev);
		centerButtons.add(next);
		rightButtons.add(summit);
		buttonPanel.add(centerButtons,BorderLayout.CENTER);
		buttonPanel.add(rightButtons,BorderLayout.EAST);
		
		JPanel pn = new CustomVerticalScrollJpanel();
		pn.setOpaque(false);
		pn.setLayout(new BoxLayout(pn,BoxLayout.PAGE_AXIS));
		pn.add(questionPanel);
		JScrollPane scroll = new JScrollPane(pn, 
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		scroll.setBorder( new EmptyBorder(0, 0, 0, 0));
		scroll.setOpaque(false);
		scroll.getViewport().setOpaque(false);
		add(scroll,BorderLayout.CENTER);
		add(buttonPanel,BorderLayout.SOUTH);
	}
	
	public void displayQuestion(int i){
		if(currentQuestion >= questions.size()-1){
			next.setEnabled(false);
		}else{
			next.setEnabled(true);
		}
		if(currentQuestion <= 0){
			prev.setEnabled(false);
		}else{
			prev.setEnabled(true);
		}
		
		this.lbCount.setText("CÂU " + (i + 1) + " :");
		this.lbQuestion.setText(this.questions.get(i).getQuestion());
		if(this.questions.get(i).getQuestionImageLink().trim().equals("")){
		}else{
			try {
				lbImage.setIcon(session.getImage(questions.get(i).getQuestionID()));
				if(lbImage.getIcon() == null){
					lbImage.setText("Nạp hình ảnh không thành công!");
				}
			} catch (RemoteException e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(getParent(), "Lỗi trong quá trình lấy ảnh từ máy chủ.", 
						"Thông báo", JOptionPane.ERROR_MESSAGE);
			}
		}
		group = new ButtonGroup();
		arrayJradio.clear();
		answerID.clear();
		answerPanel.removeAll();
		int answeredAnswer;
		try {
			answeredAnswer = session.getAnsweredAnswer(this.questions.get(i).getQuestionID());
		} catch (RemoteException e1) {
			e1.printStackTrace();
			return;
		}
		for(Entry<Integer, Answer> zzz : this.questions.get(i).getMapAnswers().entrySet()){
			if(!zzz.getValue().isShow()) continue;
			JRadioButton bt = new JRadioButton();
			JTextArea ta = new CustomJTextArea();
			ta.setText(zzz.getValue().getAnswerContent());
			bt.setOpaque(false);
			bt.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					for(int i =0; i< arrayJradio.size();i++){
						if(arrayJradio.get(i).isSelected()){
							int rs  = answerID.get(i);
							try {
								session.answerAQuestion(rs);
							} catch (RemoteException e) {
								e.printStackTrace();
							}
							break;
						}
					}
				}
			});
			group.add(bt);
			if(answeredAnswer==zzz.getKey()){
				bt.setSelected(true);
			}
			arrayJradio.add(bt);
			
			JPanel answerCell = new JPanel(new GridBagLayout());
			answerCell.setOpaque(false);
			GridBagConstraints c = new GridBagConstraints();
			c.fill = GridBagConstraints.HORIZONTAL;
			c.gridx = 0;
			c.gridy = 0;
			answerCell.add(bt,c);
			c.gridx = 1;
			c.gridy = 0;
			c.weightx = 1;
			answerCell.add(ta,c);
			answerPanel.add(answerCell);
			answerID.add(zzz.getKey());
		}
	}
	
	public void setQuestions(ArrayList<Question> questions){
		this.questions = questions;
		long seed = System.nanoTime();
		Collections.shuffle(this.questions, new Random(seed));
		currentQuestion = 0;
		displayQuestion(currentQuestion);
	}
	
	class nextAction extends AbstractAction{

		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent arg0) {
			currentQuestion++;
			displayQuestion(currentQuestion);
		}
	}
	
	class prevAction extends AbstractAction{

		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent e) {
			currentQuestion--;
			displayQuestion(currentQuestion);
		}
	}
	
	class SummitAction extends AbstractAction{

		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent e) {
			 Object[] options = { "Đồng ý!", "Thoát"};
			 int result = JOptionPane.showOptionDialog(getParent(), "Bạn thực sự muốn nộp bài thi?\n Sau khi nộp bài thi hệ thống sẽ tiến hành chấm điểm cho bài thi của bạn.",
					"Thông báo", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, 
					null, options, options[1]);
			if(result == JOptionPane.YES_OPTION){
				try {
					session.requestMarking();
					JOptionPane.showMessageDialog(getParent(), "Đã gửi yêu cầu chấm điểm lên hệ thống.",
							"Thông báo", JOptionPane.PLAIN_MESSAGE);
				} catch (RemoteException | SQLException e1) {
					JOptionPane.showMessageDialog(getParent(), "Gửi yêu cầu chấm điểm không thành công.",
							"Thông báo", JOptionPane.ERROR_MESSAGE);
					e1.printStackTrace();
				}
			}
			
		}
	}
	
	class getRightAnswers extends AbstractAction{
		
		private static final long serialVersionUID = 1L;

		@Override
		public void actionPerformed(ActionEvent e) {
			
		}
	}
}
